package com.example.music_project.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music_project.R;
import com.example.music_project.entity.SocialPost;

import java.util.ArrayList;
import java.util.List;

/*社交圈适配器*/
public class SocialPostAdapter extends RecyclerView.Adapter<SocialPostAdapter.PostViewHolder> {

    private List<SocialPost> posts = new ArrayList<>();

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_social_post, parent, false);
        return new PostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
        SocialPost post = posts.get(position);
        holder.bind(post);
    }

    @Override
    public int getItemCount() {
        return posts.size();
    }

    public void setPosts(List<SocialPost> posts) {
        this.posts = posts;
        notifyDataSetChanged();
    }

    static class PostViewHolder extends RecyclerView.ViewHolder {
        private ImageView avatar;
        private TextView username;
        private TextView content;
        private TextView time;
        private ImageView musicCover;

        // 初始化试图
        public PostViewHolder(@NonNull View itemView) {
            super(itemView);
            avatar = itemView.findViewById(R.id.img_avatar);
            username = itemView.findViewById(R.id.tv_username);
            content = itemView.findViewById(R.id.tv_content);
            time = itemView.findViewById(R.id.tv_time);
            musicCover = itemView.findViewById(R.id.img_music_cover);
        }

        // 将数据填充到 UI 库中
        public void bind(SocialPost post) {
            avatar.setImageResource(post.getAvatarResId());
            username.setText(post.getUsername());
            content.setText(post.getContent());
            time.setText(post.getTime());
            musicCover.setImageResource(post.getMusicCoverResId());
        }
    }
}